


import java.util.ArrayList;
import java.util.Collections;
import java.util.Set;


/**
 * 
 */

/**
 * Gerencia minhas formigas, controlando a populao , verificando a proximidade
 * e </br> distribuindo os interesses para cada formiga ({@link Ant})
 * 
 * @author Edgard
 * @since 02/11/2011
 */
public class AntManager {
	ArrayList<Ant> myAnts = new ArrayList<Ant>();
	ArrayList<Route> routes = new ArrayList<Route>();
	private int turn = 0;

	/**
	 * Adiciona as formigas que no estiverem na lista e dispara o mtodo
	 * cleanDeathAnts para remover </br> as formigas inativas.
	 * 
	 * @author edgardleal
	 * @since 02/11/2011
	 */
	public void refresh(Set<Tile> ants) {
		int index = -1;
		for (Tile tile : ants) {
			index = find(myAnts, tile);
			if (index < 0) {
				myAnts.add(new Ant(tile));
			} else {
				myAnts.get(index).setActive(true);
			}
		}// for
		cleanDeathAnts();
		Collections.sort(myAnts);
	}

	/**
	 * 
	 * 
	 * @author edgardleal
	 * @since 02/11/2011
	 */
	public void cleanDeathAnts() {
		if (myAnts.size() == 0)
			return;
		int index = 0;
		Ant ant = null;
		while (index < myAnts.size() && myAnts.size() > 0) {
			ant = myAnts.get(index);
			if (!ant.isActive) {
				myAnts.remove(index);
			} else
				index++;
		}
	}

	public int find(ArrayList<? extends Object> list, Tile obj) {
		for (int i = 0; i < list.size(); i++) {
			if (list.get(i).equals(obj)) {
				return i;
			}
		}
		return -1;
		// throw new RuntimeException("Formiga no encontrada " + obj + "\n"
		// + list);
	}

	public void cleanRoutes() {
		
	
	}

	public void refreshRoutes() {
		// TODO: Implementar
	}

	public static void main(String[] args) {

		AntManager manager = new AntManager();
		manager.myAnts.add(new Ant(new Tile(1, 1)));

		System.out.println(manager.myAnts.indexOf(new Tile(1, 1)));
		System.out.println(manager.myAnts.indexOf(new Ant(new Tile(1, 2))));

		System.out.println(manager.myAnts.get(0));
	}

	/**
	 * 
	 * 
	 * @author edgardleal
	 * @since 02/11/2011
	 */
	public synchronized void doTurn(Ants ants) {
		turn++;
		//Logger.log("Turn: " + turn + " ###############################");
		refresh(ants.getMyAnts());
		getOrders(ants);
	}

	/**
	 * Inclui no objeto informado {@link Ants} os comandos para este turno.
	 * 
	 * @author edgardleal
	 * @since 02/11/2011
	 * @param ants
	 */
	public void getOrders(Ants ants) {
		for (Ant ant : myAnts) {
			if (ant.getOrder(ants))// atualiza o posicionamento e direo
				ants.issueOrder(ant.getTile(), ant.getDirection());
		}
	}
}
